import React, { useState, useEffect } from 'react';
import { Modal, Form, Button, Input, Select, InputNumber,Upload,Cascader,message,Col,Checkbox, Row } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { upload } from '@/services/ant-design-pro/apis';
import {removeSysFile } from '@/services/ant-design-pro/apis';
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
import { UploadOutlined,PlusOutlined, } from '@ant-design/icons';
const { Dragger } = Upload;

const UpdateProduct = (props) => {
  const tokent = localStorage.getItem('token');
  const token = tokent == undefined ? '' : tokent;
  const [fileList, setFileList] = useState([]);
  const [archivesValue, setArchivesValue] = useState('');
  const productBrandSkuList = props.productBrandSkuList;
  const [illustrateFileList, setIllustrateFileList] = useState([]);
  const [illustrateValue, setIllustrateValue] = useState('');

  const productTypeList = props.productTypeList;
  const productCategoryVOList = props.productCategoryVOList;
  const saleChannelList= props.saleChannelList;

  const filter = (inputValue, path) => {
    return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
  };

  useEffect(() => {
    // 将逗号分隔的字符串转换为文件列表
    if (formVals.img == null) {
      return;
    }
    const archivesMap = formVals.img.split(',');
    const fileListFromString = archivesMap.map((path, index) => ({
      uid: `-${index}`, // 为每个文件生成一个唯一的uid
      name: path.split('/').pop(), // 提取文件名作为显示名
      url: path, // 文件的URL或路径
      type: 'image/jpeg',
      size: '123459',
      status: 'done', // 文件状态设置为已完成
    }));
    setArchivesValue(formVals.img);
    setFileList(fileListFromString);
  }, []); // 确保只在组件挂载时运行一次

  
  useEffect(() => {
    // 将逗号分隔的字符串转换为文件列表
    if (formVals.goodsIllustrate == null) {
      return;
    }
    const archivesMap = formVals.goodsIllustrate.split(',');
    const fileListFromString = archivesMap.map((path, index) => ({
      uid: `-${index}`, // 为每个文件生成一个唯一的uid
      name: path.split('/').pop(), // 提取文件名作为显示名
      url: path, // 文件的URL或路径
      type: 'image/jpeg',
      size: '123459',
      status: 'done', // 文件状态设置为已完成
    }));
    setIllustrateValue(formVals.goodsIllustrate);
    setIllustrateFileList(fileListFromString);
  }, []); // 确保只在组件挂载时运行一次

  const handleUpload = async ({ onSuccess, onError, file }) => {
    try {
      const uploadFile = async (file) => {
        const formData = new FormData();
        formData.append('uploadfile', file);
        const response = await fetch('/api/upLoad', {
          method: 'POST',
          body: formData,
          headers: {
            'access-control-allow-origin': '*',
            token: token,
          },
        });
        const newResponse = await response.json();
        if (newResponse && newResponse.data) {
          const path = newResponse.data;
          // 更新archivesValue，包含新上传的文件路径
          setArchivesValue((prevValue) => {
            const paths = prevValue ? prevValue.split(',') : [];
            paths.push(path);
            return paths.join(',');
          });
          onSuccess(path, file);
        } else {
          throw new Error('上传失败或返回的数据格式不正确');
        }
      };
      await uploadFile(file);
    } catch (error) {
      console.error(error);
      onError(error, file);
      message.error('文件上传失败');
    }
  };

  const handleChange = ({ fileList: newFileList }) => {
    // 使用beforeUpload来过滤文件
    const filteredFileList = newFileList.filter((file) => beforeUpload(file));
    console.log(archivesValue);
    setFileList(filteredFileList.length > 0 ? filteredFileList : fileList);
  };

  const handleRemove = (file) => {
    const index = fileList.indexOf(file);

    if (index === -1) {
      console.error('文件不在列表中');
      return;
    }

    const paths = archivesValue.split(',');
    const element = paths[index];
    const fileName = element.split('/').pop().split('\\').pop(); // 提取文件名

    const removeFile = async () => {
      const hide = message.loading('正在删除');
      try {
        await removeSysFile(fileName);
        hide();
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        setFileList(newFileList);

        setArchivesValue((prevValue) => {
          const paths = archivesValue.split(',');
          if (index !== -1) {
            paths.splice(index, 1);
          }
          if (paths.index !== -1) {
            return paths.join(',');
          } else {
            setArchivesValue(undefined);
          }
        });
        message.success('删除成功');
      } catch {
        hide();
        message.error('删除失败');
      }
    };
    removeFile();
  };

  const handleUploadT = async ({ onSuccess, onError, file }) => {
    try {
      const uploadFile = async (file) => {
        const formData = new FormData();
        formData.append('uploadfile', file);
        const response = await fetch('/api/upLoad', {
          method: 'POST',
          body: formData,
          headers: {
            'access-control-allow-origin': '*',
            token: token,
          },
        });
        const newResponse = await response.json();
        if (newResponse && newResponse.data) {
          const path = newResponse.data;
          // 更新archivesValue，包含新上传的文件路径
          setIllustrateValue((prevValue) => {
            const paths = prevValue ? prevValue.split(',') : [];
            paths.push(path);
            return paths.join(',');
          });
          onSuccess(path, file);
        } else {
          throw new Error('上传失败或返回的数据格式不正确');
        }
      };
      await uploadFile(file);
    } catch (error) {
      console.error(error);
      onError(error, file);
      message.error('文件上传失败');
    }
  };

  const handleChangeT = ({ fileList: newFileList }) => {
    // 使用beforeUpload来过滤文件
    const filteredFileList = newFileList.filter((file) => beforeUpload(file));
    setIllustrateFileList(filteredFileList.length > 0 ? filteredFileList : fileList);
  };

  const handleRemoveT = (file) => {
    const index = fileList.indexOf(file);

    if (index === -1) {
      console.error('文件不在列表中');
      return;
    }

    const paths = illustrateValue.split(',');
    const element = paths[index];
    const fileName = element.split('/').pop().split('\\').pop(); // 提取文件名

    const removeFile = async () => {
      const hide = message.loading('正在删除');
      try {
        await removeSysFile(fileName);
        hide();
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        setIllustrateFileList(newFileList);

        setIllustrateValue((prevValue) => {
          const paths = archivesValue.split(',');
          if (index !== -1) {
            paths.splice(index, 1);
          }
          if (paths.index !== -1) {
            return paths.join(',');
          } else {
            setIllustrateValue(undefined);
          }
        });
        message.success('删除成功');
      } catch {
        hide();
        message.error('删除失败');
      }
    };
    removeFile();
  };

  const beforeUpload = (file) => {
    // 阻止自动上传，如果需要的话，你可以在这里处理图片上传逻辑
    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPGorPNG) {
      message.error('只能上传 JPG 或 PNG 格式图片!');
      return false;
    }
    const isLt10K = file.size < 300 * 1024;
    if (!isLt10K) {
      message.error('图片大小不能超过 300KB!');
      return false;
    }
    return true;
  };


  const intiBrandSku = () => {
    var productBrandSkuList = [];
    if (formVals.brandId != null && formVals.brandId != undefined && formVals.brandId >= 1) {
      productBrandSkuList.push(formVals.brandId);
      if (
        formVals.brandSkuId != null &&
        formVals.brandSkuId != undefined &&
        formVals.brandSkuId >= 1
      ) {
        productBrandSkuList.push(formVals.brandSkuId);
      }
    }
    return productBrandSkuList;
  };

  
  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const { onSubmit: handleUpdate, onCancel: handleModalVisible, updateModalVisible } = props;

  const [formVals, setFormVals] = useState({
    id: props.values.id,
    goodsName: props.values.goodsName,
    goodsCode: props.values.goodsCode,
    status: props.values.status,
    price: props.values.price,
    goodsSort: props.values.goodsSort,
    goodsTypeId: props.values.goodsTypeId,
    stockNum: props.values.stockNum,
    limitPrice: props.values.limitPrice,
    faceValue:props.values.faceValue,
    brandId:props.values.brandId,
    brandSkuId:props.values.brandSkuId,
    img:props.values.img,
    channels: props.values.channels,
    goodsIllustrate:props.values.goodsIllustrate
  });

  const channels = props.channels;

  const handleSubmit = async () => {
    try {
      const fieldVlas = await form.validateFields();
      fieldVlas.img = archivesValue;
      handleUpdate({ ...fieldVlas });
      onReset();
    } catch (err) {
      console.log(err);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  const [form] = Form.useForm();

  return (
    <Modal
      title="配置产品"
      width={540}
      visible={updateModalVisible}
      destroyOnClose
      onCancel={() => {
        onReset();
        handleModalVisible(false);
      }}
      footer={[
        <Button
          key="reset"
          onClick={() => {
            handleModalVisible();
          }}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="submit"
          onClick={() => {
            handleSubmit();
          }}
        >
          提交
        </Button>,
      ]}
    >
      <Form
        {...formLayout}
        initialValues={{
          goodsName: formVals.goodsName,
          goodsCode: formVals.goodsCode,
          status: formVals.status,
          price: formVals.price,
          goodsSort: formVals.goodsSort,
          goodsTypeId: formVals.goodsTypeId,
          stockNum: formVals.stockNum,
          limitPrice: formVals.limitPrice,
          faceValue: formVals.faceValue,
          productBrandSku: intiBrandSku(),
          channels:formVals.channels,
          goodsIllustrate:formVals.goodsIllustrate,
        }}
        form={form}
      >
        <FormItem
          label="产品名称"
          name="goodsName"
          rules={[
            {
              required: true,
              message: '产品名称是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品名称"></Input>
        </FormItem>
        <FormItem
          label="产品编码"
          name="goodsCode"
          rules={[
            {
              required: true,
              message: '产品编码是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品编码" rows={4} />
        </FormItem>
        <FormItem
          label="面值价(元)"
          name="faceValue"
          rules={[
            {
              required: true,
              message: '面值价是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入面值价" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="售价(元)"
          name="price"
          rules={[
            {
              required: true,
              message: '售价是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入售价" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="终端限价(元)"
          name="limitPrice"
          rules={[
            {
              required: true,
              message: '终端限价是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入终端限价" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="库存"
          name="stockNum"
          rules={[
            {
              required: true,
              message: '售价是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入售价" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="产品类型"
          name="goodsTypeId"
          rules={[
            {
              required: true,
              message: '产品类型是必须项',
            },
          ]}
        >
          <Select placeholder="请选择产品类型">
            {productTypeList?.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.label}
                </Option>
              );
            })}
          </Select>
        </FormItem>
        <FormItem
          label="产品分类"
          name="productBrandSku"
          rules={[
            {
              required: true,
              message: '产品分类是必须项',
            },
          ]}
        >
          <Cascader
            options={productCategoryVOList}
            placeholder="请选择分类"
            showSearch={{
              filter,
            }}
          />
        </FormItem>


        
        <FormItem label="状态" name="status">
          <Select>
            <Option value={99}>上架</Option>
            <Option value={-99}>下架</Option>
          </Select>
        </FormItem>
                <FormItem label="排序值" name="goodsSort">
                <InputNumber   style={{ width: '100%' }}

            placeholder="请输入排序值(值越大越靠前)"
          />
                </FormItem>
                <FormItem label="售卖渠道" name="channels">
          <Checkbox.Group>
            <Row>
              {saleChannelList?.map((item) => {
                return (
                  <Col key={item.value}>
                    <Checkbox value={item.value} style={{ lineHeight: '32px' }}>
                      {item.label}
                    </Checkbox>
                  </Col>
                );
              })}
            </Row>
          </Checkbox.Group>
        </FormItem>
                <Form.Item
          label="产品图片"
          name="img"
          initialValue={archivesValue} // 设置初始值
        >
          <Upload
            action="" // 替换为你的实际图片上传接口地址
            listType="picture-card"
            fileList={fileList}
            //onPreview={handlePreview}
            onChange={handleChange}
            beforeUpload={beforeUpload}
            onRemove={handleRemove}
            customRequest={handleUpload}
          >
            {fileList.length < 1 && (
              <div>
                <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </button>

              </div>
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          label="产品说明"
          name="goodsIllustrate"
          initialValue={archivesValue} // 设置初始值
        >
          <Upload
            action="" // 替换为你的实际图片上传接口地址
            listType="picture-card"
            fileList={illustrateFileList}
            //onPreview={handlePreview}
            onChange={handleChangeT}
            beforeUpload={beforeUpload}
            onRemove={handleRemoveT}
            customRequest={handleUploadT}
          >
            {illustrateFileList.length < 1 && (
              <div>
                <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </button>

              </div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UpdateProduct;
